<?php
namespace Admin\Controller;

use Admin\Controller\BaseController;

/**
 * 权限管理
 *
 * @author ryan
 *        
 */
class LimitsController extends BaseController
{

    public function roleList()
    {
        if (IS_POST) {
            $page = I('page');
            $limit = I('limit');
            $condition = array();
            $list = D('Role')->where($condition)
                ->page($page, $limit)
                ->select();
            $count = D('Role')->where($condition)->count();
            $msg = '';
            if (empty($count)) {
                $msg = '暂无记录';
            }
            $result = array(
                'code' => 0,
                'msg' => $msg,
                'count' => $count,
                'data' => $list
            );
            $this->ajaxReturn($result);
        }
        $this->display('Limits/roles');
    }

    public function addRole()
    {
        if (IS_POST) {
            $info = I('info');
            if (empty($info['role_name'])) {
                $this->error('角色名称不能为空');
            }
            $role = D('Role')->where(array(
                'role_name' => $info['role_name']
            ))->find();
            if (! empty($role)) {
                $this->error('该角色已存在');
            }
            $info['status'] = 0;
            $info['add_time'] = TIMESTAMP;
            $status = D('Role')->add($info);
            if ($status === false) {
                $this->error('添加失败');
            } else {
                $this->success('添加成功');
            }
        }
        $this->display();
    }

    public function editRole()
    {
        $nid = I('nid');
        if (empty($nid)) {
            $this->error('异常操作');
        }
        $role = D('Role')->where(array(
            'id' => $nid
        ))->find();
        if (empty($role)) {
            $this->error('数据异常');
        }
        if (IS_POST) {
            $info = I('info');
            if ($role['role_name'] == $info['role_name'] && $role['remark'] == $info['remark']) {
                $this->error('内容无更改');
            }
            $temp = D('Role')->where(array(
                'role_name' => $info['role_name'],
                'id' => array(
                    'neq',
                    $nid
                )
            ))->find();
            if (! empty($temp)) {
                $this->error('该角色名称已经存在');
            }
            $status = D('Role')->where(array(
                'id' => $nid
            ))->save($info);
            if ($status === false) {
                $this->error('修改失败');
            } else {
                $this->success('修改成功');
            }
        }
        $this->assign('role', $role);
        $this->display();
    }

    public function editRoleStatus()
    {
        $nid = I('nid');
        if (empty($nid)) {
            $this->error('异常操作');
        }
        $state = I('state');
        $status = D('Role')->where(array(
            'id' => $nid
        ))->save(array(
            'status' => $state
        ));
        if ($status === false) {
            $this->error('修改失败');
        } else {
            $this->success('修改成功');
        }
    }

    /**
     * 角色授权
     */
    public function rolePrivilege()
    {
        $nid = I('nid');
        if (empty($nid)) {
            $this->error('异常操作');
        }
        if (IS_POST) {
            $type = I('type');
            $privilege_id = I('privilege_id');
            if ($type == 'privilege') {
                $privileges = D('PrivilegeMenu')->where(array(
                    'privilege_id' => $privilege_id
                ))->select();
                $menus = D('Menu')->menus_privilege($privileges);
                $this->ajaxReturn($menus);
            } else {
                if (empty($privilege_id)) {
                    $this->error('请选择权限组');
                }
                $privilege = D('RolePrivilege')->where(array(
                    'role_id' => $nid
                ))->find();
                if (empty($privilege)) {
                    $status = D('RolePrivilege')->add(array(
                        'role_id' => $nid,
                        'privilege_id' => $privilege_id,
                        'add_time' => TIMESTAMP
                    ));
                    if ($status === false) {
                        $this->error('授权失败');
                    } else {
                        $this->success('授权成功');
                    }
                } else {
                    $status = D('RolePrivilege')->where(array(
                        'id' => $privilege['id']
                    ))->save(array(
                        'privilege_id' => $privilege_id
                    ));
                    if ($status === false) {
                        $this->error('授权失败');
                    } else {
                        $this->success('授权成功');
                    }
                }
            }
        }
        $privileges = D('Privilege')->where(array(
            'status' => 0
        ))->select();
        $privilege = D('RolePrivilege')->where(array(
            'role_id' => $nid
        ))->find();
        $this->assign('privileges', $privileges);
        $this->assign('privilege', $privilege);
        $this->assign('nid', $nid);
        $this->display();
    }

    public function privileges()
    {
        if (IS_POST) {
            $page = I('page');
            $limit = I('limit');
            $condition = array();
            $list = D('Privilege')->where($condition)
                ->page($page, $limit)
                ->select();
            $count = D('Role')->where($condition)->count();
            $msg = '';
            if (empty($count)) {
                $msg = '暂无记录';
            }
            $result = array(
                'code' => 0,
                'msg' => $msg,
                'count' => $count,
                'data' => $list
            );
            $this->ajaxReturn($result);
        }
        $this->display();
    }

    public function addPrivilege()
    {
        if (IS_POST) {
            $info = I('info');
            if (empty($info['privilege_name'])) {
                $this->error('权限组名称不能为空');
            }
            $privilege = D('Privilege')->where(array(
                'privilege_name' => $info['privilege_name']
            ))->find();
            if (! empty($privilege)) {
                $this->error('权限组名称已存在');
            }
            $info['status'] = 0;
            $info['add_time'] = TIMESTAMP;
            $status = D('Privilege')->add($info);
            if ($status === false) {
                $this->error('添加失败');
            } else {
                $this->success('添加成功');
            }
        }
        $this->display();
    }

    public function editPrivilege()
    {
        $nid = I('nid');
        if (empty($nid)) {
            $this->error('异常操作');
        }
        $privilege = D('Privilege')->where(array(
            'id' => $nid
        ))->find();
        if (empty($privilege)) {
            $this->error('数据异常');
        }
        if (IS_POST) {
            $info = I('info');
            if (empty($info['privilege_name'])) {
                $this->error('权限组名称不能为空');
            }
            $temp = D('Privilege')->where(array(
                'privilege_name' => $info['privilege_name'],
                'id' => array(
                    'neq',
                    $nid
                )
            ))->find();
            if (! empty($temp)) {
                $this->error('该权限组名称已存在');
            }
            $status = D('Privilege')->where(array(
                'id' => $nid
            ))->save($info);
            if ($status === false) {
                $this->error('修改失败');
            } else {
                $this->success('修改成功');
            }
        }
        $this->assign('privilege', $privilege);
        $this->display();
    }

    public function editPrivilegeStatus()
    {
        $nid = I('nid');
        if (empty($nid)) {
            $this->error('异常操作');
        }
        $state = I('state');
        $status = D('Privilege')->where(array(
            'id' => $nid
        ))->save(array(
            'status' => $state
        ));
        if ($status === false) {
            $this->error('修改失败');
        } else {
            $this->success('修改成功');
        }
    }

    /**
     * 权限分配
     */
    public function privilegeAllot()
    {
        $nid = I('nid');
        if (empty($nid)) {
            $this->error('异常操作');
        }
        if (IS_POST) {
            $info = I('info');
            if (empty($info)) {
                $this->error('权限数据出错');
            }
            foreach ($info as $key => $value) {
                $value['privilege_id'] = $nid;
                $value['add_time'] = TIMESTAMP;
                $info[$key] = $value;
            }
            D()->startTrans();
            $delete = D('PrivilegeMenu')->where(array(
                'privilege_id' => $nid
            ))->delete();
            if ($delete === false) {
                D()->rollback();
                $this->error('保存失败');
            }
            $status = D('PrivilegeMenu')->addAll($info);
            if ($status === false) {
                D()->rollback();
                $this->error('保存失败');
            } else {
                D()->commit();
                $this->success('保存成功');
            }
        }
        $menus = D('Menu')->menusTree(array(
            'pid' => 0,
            'status' => 0
        ));
        $privileges = D('PrivilegeMenu')->where(array(
            'privilege_id' => $nid
        ))->select();
        $menus = $this->menu_privilege($menus, $privileges);
        $this->assign('privileges', json_encode($privileges));
        $this->assign('nid', $nid);
        $this->assign('menus', json_encode($menus));
        $this->display();
    }

    /**
     * 用户组管理
     */
    public function userGroup()
    {
        if (IS_POST) {}
        $this->display();
    }

    public function addUserGroup()
    {
        $this->display();
    }

    /**
     * 用户列表
     */
    public function userList()
    {
        if (IS_POST) {
            $page = I('page');
            $limit = I('limit');
            $condition = array();
            $condition['is_admin'] = array(
                'neq',
                1
            );
            $list = D('User')->where($condition)
                ->page($page, $limit)
                ->select();
            $count = D('User')->where($condition)->count();
            $msg = '';
            if (empty($count)) {
                $msg = '暂无记录';
            }
            $result = array(
                'code' => 0,
                'msg' => $msg,
                'count' => $count,
                'data' => $list
            );
            $this->ajaxReturn($result);
        }
        $this->display();
    }

    /**
     * 添加用户
     */
    public function addUser()
    {
        if (IS_POST) {
            $info = I('info');
            if (empty($info['username'])) {
                $this->error('登录账号不能为空');
            }
            if (empty($info['password'])) {
                $this->error('密码不能为空');
            }
            $user = D('User')->where(array(
                'username' => $info['username']
            ))->find();
            if (! empty($user)) {
                $this->error('该登录账号已存在');
            }
            $info['password'] = md5($info['password']);
            $info['add_time'] = TIMESTAMP;
            $role_id = $info['role_id'];
            unset($info['role_id']);
            D()->startTrans();
            $insert_id = D('User')->add($info);
            if ($insert_id === false) {
                D()->rollback();
                $this->error('添加失败');
            }
            $status = D('RoleUser')->add(array(
                'role_id' => $role_id,
                'user_id' => $insert_id,
                'add_time' => TIMESTAMP
            ));
            if ($status === false) {
                D()->rollback();
                $this->error('添加用户失败');
            } else {
                D()->commit();
                $this->success('添加用户成功');
            }
        }
        $roles = D('Role')->where(array(
            'status' => 0
        ))->select();
        $this->assign('roles', $roles);
        $this->display();
    }

    public function editUser()
    {
        $nid = I('nid');
        if (empty($nid)) {
            $this->error('异常操作');
        }
        $user = D('User')->where(array(
            'id' => $nid
        ))
            ->relation(true)
            ->find();
        if (empty($user)) {
            $this->error('用户不存在');
        }
        if (IS_POST) {}
        $roles = D('Role')->where(array(
            'status' => 0
        ))->select();
        $this->assign('user', $user);
        $this->assign('roles', $roles);
        $this->display();
    }

    public function disabledUser()
    {}

    private function menu_privilege($menus, $privileges)
    {
        foreach ($menus as $key => $menu) {
            $checked = false;
            foreach ($privileges as $privilege) {
                if ($privilege['menu_id'] == $menu['value']) {
                    $checked = true;
                    break;
                }
            }
            $menu['checked'] = $checked;
            if ($menu['is_default'] == 1) {
                $menu['checked'] = true;
                $menu['disabled'] = true;
            }
            if (! empty($menu['data'])) {
                $menu['data'] = $this->menu_privilege($menu['data'], $privileges);
            }
            $menus[$key] = $menu;
        }
        return $menus;
    }
}

